package com.ciaojian.bytedance.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaojian.bytedance.service.ByteDancePayService;
import com.ciaojian.bytedance.service.MemberServiceImpl;
import com.ciaojian.bytedance.vo.bytedance.*;
import com.ciaojian.core.base.annotation.ApiIdempotent;
import com.ciaojian.core.enums.business.OrderIsUserMemberEnum;
import com.ciaojian.core.enums.business.OrderOrderTypeEnum;
import com.ciaojian.core.enums.business.OrderStatusEnum;
import com.ciaojian.core.mapper.OrderMapper;
import com.ciaojian.core.mapper.UserMemberMapper;
import com.ciaojian.core.model.Order;
import com.ciaojian.core.model.Store;
import com.ciaojian.core.model.UserMember;
import com.ciaojian.core.model.Worker;
import com.ciaojian.core.model.dy.DyOrder;
import com.ciaojian.core.service.UserMemberService;
import com.ciaojian.core.util.Result;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

@ApiModel("小程序商品支付接口")
@Slf4j
@RestController
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private ByteDancePayService byteDancePayService;
    @Resource
    private UserMemberMapper userMemberMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private MemberServiceImpl memberService;

    @ApiOperation("抖音回调设置接口")
    @PostMapping("/notifySettings")
    public JSONObject notifySettings(HttpRequest httpRequest) throws Exception {
        return byteDancePayService.notifySettings(httpRequest);

    }

    @ApiOperation("抖音回调接口查询")
    @GetMapping("/query_settings")
    public JSONObject querySettings(HttpRequest httpRequest) throws Exception {
        return byteDancePayService.querySettings(httpRequest);
    }


    /**
     * 查看是否已经购买
     *
     * @return
     * @throws Exception
     */
    @ApiOperation("查看是否已经购买")
    @GetMapping("/check_order")
    public Result check_order(@ApiParam("用户表id") Integer userId) throws Exception {
        return byteDancePayService.check_order(userId);

    }
    @ApiModelProperty("新老用户")
    @GetMapping("/check_user")
    public Result check_user(@RequestParam Integer userId) throws Exception {
        QueryWrapper<UserMember> userMemberQueryWrapper = new QueryWrapper<>();
        userMemberQueryWrapper.eq("user_id",userId);
        UserMember userMember = userMemberMapper.selectOne(userMemberQueryWrapper);
        // 如果没数据表示从未开过会员
        if (userMember == null) {
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("user_id",userId);
            orderQueryWrapper.in("status",3,5,-2);
            Integer count = orderMapper.selectCount(orderQueryWrapper);
            if (count<2) {
                return Result.ok(true);
            }
        }
        return Result.ok(false);
    }


    @ApiModelProperty("新老用户")
    @GetMapping("/check_member")
    public Result check_member(@RequestParam Integer userId,@RequestParam String goodsId) throws Exception {
        QueryWrapper<UserMember> userMemberQueryWrapper = new QueryWrapper<>();
        userMemberQueryWrapper.eq("user_id",userId);
        UserMember userMember = userMemberMapper.selectOne(userMemberQueryWrapper);
        // 如果没数据表示从未开过会员
        if (userMember == null) {
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("user_id",userId);
            orderQueryWrapper.in("status",3,5,-2);
            Integer count = orderMapper.selectCount(orderQueryWrapper);
            if (count<2) {
                if ("7199532669212919840".equals(goodsId)){
                    return Result.ok("128新客",102);
                }
                if ("7199528377485232163".equals(goodsId)){
                    return Result.ok("168新客",100);
                }
            }
        }
        if ("7199532669212919840".equals(goodsId)){
            return Result.ok("128老客",103);
        }
        if ("7199528377485232163".equals(goodsId)){
            return Result.ok("168老客",101);
        }
        return Result.ok(null);
    }

    /**
     * 查看支付订单
     */
    @ApiOperation("查看支付订单")
    @PostMapping("/v1/query_order")
    public JSONObject query_order_v1(@ApiParam("订单号") String orderNo) throws Exception {
        return byteDancePayService.query_order_v1(orderNo);

    }


    /**
     * 担保支付发起
     */
    @ApiOperation("担保支付发起")
    @PostMapping("/v1/create_order")
    @ApiIdempotent
    public Result create_order_v1(HttpServletRequest request,
                                 @RequestBody OrderCreateRequestVo orderCreateRequestVo) throws Exception {
        return byteDancePayService.create_order_v1(request,orderCreateRequestVo);

    }





    @ApiOperation("预下单回调")
    @PostMapping("/create_order/notify")
    public ByteDanceOrderNotifyResponseVo createOrderNotify(@RequestBody NotifyVo createOrderNotifyVo) throws Exception {
        return byteDancePayService.createOrderNotify(createOrderNotifyVo);
    }

    @ApiOperation("订单详情")
    @GetMapping("/query_order")
    public Result queryOrder(String orderId) throws Exception {
        return byteDancePayService.queryOrder(orderId);
    }

    //核销组件二维码跳转地址
    @ApiOperation("抖音二维码回调接口")
    @GetMapping("/verific")
    public Result verificNotify(@RequestParam(required = false) String encrypted_data, @RequestParam(required = false) String app_id,
                                @RequestParam(required = false) String out_order_no, @RequestParam(required = false) String code) throws Exception {
        return byteDancePayService.verificNotify(encrypted_data,app_id,out_order_no,code);
    }

    /**
     * 抖音核销接口
     *
     * @param orderNo
     * @param workerId
     * @param storeId
     * @return
     * @throws Exception
     */
    @ApiOperation("抖音核销接口")
    @GetMapping("/postverify")
    public Result postverifyNotify(@RequestParam String orderNo,
                                   @RequestParam String workerId,
                                   @RequestParam String storeId
    ) throws Exception {
        return byteDancePayService.postverifyNotify(orderNo,workerId,storeId);

    }

    @ApiOperation("抖音核销接口")
    @GetMapping("/postverifyCS")
    @Transactional
    public Result postverifyCS(@RequestParam String orderNo,
                                   @RequestParam String workerId,
                                   @RequestParam String storeId
    ) throws Exception {
        QueryWrapper<DyOrder> dyOrderMapperQueryWrapper = new QueryWrapper<>();
        dyOrderMapperQueryWrapper.eq("order_no", orderNo);
        DyOrder dyOrder = new DyOrder().selectOne(dyOrderMapperQueryWrapper);
        Worker worker = new Worker().selectById(workerId);
        Store store = new Store().selectById(storeId);

        if (ObjectUtil.isNotNull(dyOrder.getMemberId())&&dyOrder.getMemberId()!=0) {
            memberService.send(dyOrder, worker);
            dyOrder.setStoreId(store.getId());
            dyOrder.setStoreName(store.getTitle());
            dyOrder.setStatus(5);
            dyOrder.setVefiTime(new Date());
            dyOrder.updateById();


            Order order = new Order();
            order.setUserId(dyOrder.getUserId());
            order.setStoreName(store.getTitle());
            order.setWorkerName(dyOrder.getWorkerName());
            order.setWorkerId(dyOrder.getWorkerId());
            order.setStoreId(dyOrder.getStoreId());
            order.setType(dyOrder.getType());
            order.setGoodsTotal(new BigDecimal(0));
            order.setTotal(new BigDecimal(0));
            order.setOrderNo(dyOrder.getOrderNo());
            order.setAddTime(new Date());
            order.setPayTime(dyOrder.getPayTime());
            order.setPayTotal(new BigDecimal(0));
            order.setStatus(OrderStatusEnum.complete);
            order.setPayType(dyOrder.getPayType());
            if (ObjectUtil.isNotNull(dyOrder.getDyCode())) {
                order.setYouzanCode(dyOrder.getDyCode());
            }
            order.setChannel(2);
            order.setOrderType(OrderOrderTypeEnum.MEMBER_DETAIL);
            order.setUpdateTime(dyOrder.getVefiTime());
            if (dyOrder.getIsUserMember()==1){
                order.setIsUserMember(OrderIsUserMemberEnum.VALID_MEMBER);
            }else if(dyOrder.getIsUserMember()==0){
                order.setIsUserMember(OrderIsUserMemberEnum.EXPIRED_MEMBER);
            }else if(dyOrder.getIsUserMember()==-1){
                order.setIsUserMember(OrderIsUserMemberEnum.NON_MEMBER);
            }
            order.insert();
        }
        return Result.ok();
    }

    /**
     * 退款回调接口
     *
     * @param refundCallbackVo
     * @return
     */
    @ApiOperation("退款回调接口")
    @PostMapping("/refundnotify")
    public ByteDanceRefundNotifyResponseVo refundNotify(@RequestBody NotifyVo refundCallbackVo) {
        return byteDancePayService.refundNotify(refundCallbackVo);

    }


    @ApiOperation("退款审核结果同步")
    @GetMapping("/merchant_audit")
    public JSONObject merchantAudit(@ApiParam("订单号") @RequestParam String outRefundNo,
                                    @ApiParam("退款状态 1同意 2拒绝") @RequestParam Integer status,
                                    @ApiParam("拒绝原因") @RequestParam(required = false) String message) throws Exception {
        return byteDancePayService.merchantAudit(outRefundNo,status,message);

    }

    @ApiOperation("退款单查询")
    @GetMapping("/query_refund")
    public JSONObject queryRefund(@ApiParam("外部订单号") @RequestParam(required = false) String orderNo) throws Exception {
        return byteDancePayService.queryRefund(orderNo);

    }
}
